package com.jxb.demo.im.client;

import com.jxb.demo.im.MsgPackDecoder;
import com.jxb.demo.im.MsgPackEncoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import java.util.concurrent.TimeUnit;

/**
 * @desc 客户端实现
 */
public class IMClient {

    /**
     * @desc 客户端连接服务端
     */
    public void connect(String host,int port){
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.TCP_NODELAY,true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        //消息体长度编码
                        pipeline.addLast(new LengthFieldPrepender(2));
                        pipeline.addLast(new MsgPackEncoder());
                        //消息解码器
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(65532,0,2,0,2));
                        pipeline.addLast(new MsgPackDecoder());
                        pipeline.addLast(new IMClientHandler());
                    }
                });
        try{
            //直到连接返回才会退出当前线程
            ChannelFuture channelFuture = bootstrap.connect(host,port).sync().addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(!channelFuture.isSuccess()){
                        EventLoop eventLoop = channelFuture.channel().eventLoop();
                        eventLoop.schedule(()->connect("127.0.0.1",8080),3,TimeUnit.SECONDS);
                    }
                }
            });

            channelFuture.channel().closeFuture().sync();//直到channel关闭，才会退出当前线程

        }catch (Exception e){
            e.printStackTrace();
        }finally{
            //workerGroup.shutdownGracefully();
            connect("127.0.0.1",8080);
        }
    }

    public static void main(String[] args) {
        new IMClient().connect("127.0.0.1",8080);
    }

}
